import router from '@/router'
import store from '@/store';
import axios from 'axios';
import qs from 'qs';
import vm from "@/main.js";
import tools from "@/utils/index.js";
// import {domain} from '@/config/config';
const domain = process.env.NODE_ENV == "production" ? "//zlhrapi-test.hrzhuolin.cn" :""; 

const methods = ['get', 'post'];

console.log("domain",domain);
// cookie

class Http {
    constructor() {
        methods.forEach(method => {
            this[method] = (url, { params = {}, data = {} } = {}) => {
                return new Promise((resolve, reject) => {
                    const request = axios.create();
                    const token = tools.cookie.get("token");
                    if(token ){
                        if(!url.includes("login") ||
                         !url.includes("sendsms")  || !url.includes("register") ){
                            params.token = token
                        }
                    }

                    let option = {
                        baseURL: domain,
                        method,
                        url,
                        timeout: 15000,
                        params: method === "get" ? {
                            ...params
                        } : params,
                        data: qs.stringify({
                            ...data
                        }),
                        
                    
                    }
                    // request.defaults.headers['Content-Type'] = "application/json"
                    request(option).then((res) => {

                        if (res.data) {
                            if (res.data.e === '9998') {//登录过期或者未登录
                                //location.href = "/login?returnUrl=" + location.href;
                                //location.href = "/login";
                                if(url.includes("register") || url.includes("login")){
                                    return resolve(res.data)
                                }else{
                                    location.href = "/login";
                                }
                            } else if (res.data.e === '9999') {
                                return resolve(res.data)
                            } else {//报错
                                vm.$Message.error(res.data.m);
                            }

                        } else {
                            reject(res.error)
                        }
                    }).catch((e) => {
                        console.log(e);
                    })
                })
            }
        });
    }
}

const http = new Http();
export default http;